package com.trade.service.impl;

import java.util.List;

import com.trade.dao.IProcurmentContractDao;
import com.trade.exception.BusinessException;
import com.trade.exception.PersistenceException;
import com.trade.model.ProcurmentContract;
import com.trade.service.IProcurmentContractService;

/**
 * @author Lin Yang
 * 
 */
public class ProcurmentContractServiceImpl implements IProcurmentContractService {
    private IProcurmentContractDao procurmentContractDao;

    @Override
    public ProcurmentContract getProcurmentContractById(long id) throws BusinessException {
        return procurmentContractDao.get(id);
    }

    @Override
    public void saveProcurmentContract(ProcurmentContract contract) throws BusinessException {
        procurmentContractDao.save(contract);
    }

    @Override
    public List<ProcurmentContract> getContractLikeName(String name) throws BusinessException {
        try {
            return procurmentContractDao.findLikeName(name);
        } catch (PersistenceException e) {
            throw new BusinessException(e);
        }
    }

    @Override
    public List<ProcurmentContract> getApprovingContractLikeName(String name) throws BusinessException {
        try {
            return procurmentContractDao.findByStateAndLikeName(ProcurmentContract.STATE_SUBMIT, name);
        } catch (PersistenceException e) {
            throw new BusinessException(e);
        }
    }

    @Override
    public List<ProcurmentContract> getVerifyingContractLikeName(String name) throws BusinessException {
        try {
            return procurmentContractDao.findByStateAndLikeName(ProcurmentContract.STATE_APPROVE, name);
        } catch (PersistenceException e) {
            throw new BusinessException(e);
        }
    }

    @Override
    public void approveContract(ProcurmentContract contract) throws BusinessException {
        double cost = contract.getTotalCost();
        if (Double.compare(cost, 500000) > 0) {
            contract.setState(ProcurmentContract.STATE_APPROVE);
        } else {
            contract.setState(ProcurmentContract.STATE_COMPLETE);
        }
        procurmentContractDao.update(contract);
    }

    @Override
    public void verifyContract(ProcurmentContract contract) throws BusinessException {
        contract.setState(ProcurmentContract.STATE_COMPLETE);
        procurmentContractDao.update(contract);
    }

    public void setProcurmentContractDao(IProcurmentContractDao procurmentContractDao) {
        this.procurmentContractDao = procurmentContractDao;
    }

}
